package com.hw.hcit.feature;

import com.hw.hcit.conf.CompassView;
import com.hw.hcit.conf.Config;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.hw.hcit.conf.JTestItem;
import com.hw.hcit.R;

public class CompassTestItem extends JTestItem {

    final static int MENU_QUIT = 1;
    CompassView view;
    private Button successButton, failButton;
    TextView mDirectionLayout;// 显示方向（东南西北）的view
    TextView mAngleLayout;// 显示方向度数的view
    private Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // 表面屏幕自动翻转导致的错位问题
        // 效果与AndroidManifest.xml 设置android:screenOrientation 属性一样
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        // LocationManager myLocationManager=null;
        // myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        // Location l = myLocationManager.getLastKnownLocation("network");
        // String url = l.getLatitude() + "," + l.getLongitude(); 这里获取到了精度和维度
        View rootView = inflater.inflate(R.layout.compass_test, container,
                false);
        view = (CompassView) rootView.findViewById(R.id.compass_view);
        successButton = (Button) rootView.findViewById(R.id.success_test);
        failButton = (Button) rootView.findViewById(R.id.fail_test);
        mDirectionLayout = (TextView) rootView
                .findViewById(R.id.layout_direction);// 顶部显示方向名称（东南西北）的LinearLayout
        mAngleLayout = (TextView) rootView.findViewById(R.id.layout_angle);// 顶部显示方向具体度数的LinearLayout

        successButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
            	if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(27, 'P');
					} else {
						rewriteOneByteOfNv2499(58, 'P');
					}
				}
				 testFinish(true, 1, true);

            }
        });
        failButton.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
            	if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(27, 'P');
					} else {
						rewriteOneByteOfNv2499(58, 'P');
					}
				}
				 testFinish(true, 1, true);

            }
        });
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        mContext = activity;
    }

    protected final Handler mHandler = new Handler();

    // 这个是更新指南针旋转的线程，handler的灵活使用，每20毫秒检测方向变化值，对应更新指南针旋转
    protected Runnable mCompassViewUpdater = new Runnable() {
        @Override
        public void run() {
            updateDirection();// 更新方向值

            mHandler.postDelayed(mCompassViewUpdater, 20);// 20毫米后重新执行自己，比定时器好
        }
    };

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mHandler.postDelayed(mCompassViewUpdater, 20);
    }

    // 更新顶部方向显示的方法
    private void updateDirection() {
        Float mTargetDirection = 0.0f;
        if (view != null) {
            mTargetDirection = view.getTargetDirection();
        }
        Log.d("CJ", "mTargetDirection=" + mTargetDirection);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        // 先移除layout中所有的view
        mDirectionLayout.setText("");
        mAngleLayout.setText("");

        // 下面是根据mTargetDirection，作方向名称图片的处理
        ImageView east = null;
        ImageView west = null;
        ImageView south = null;
        ImageView north = null;
        float direction = normalizeDegree(mTargetDirection * -1.0f);
        if (direction > 22.5f && direction < 157.5f) {
            // east
            mDirectionLayout.setText("E");
        } else if (direction > 202.5f && direction < 337.5f) {
            // west
            mDirectionLayout.setText("W");
        }

        if (direction > 112.5f && direction < 247.5f) {
            // south
            mDirectionLayout.setText("S");
        } else if (direction < 67.5 || direction > 292.5f) {
            // north
            mDirectionLayout.setText("N");
        }
        // east/west should be before north/south
        /*
         * if (east != null) { mDirectionLayout.addView(east); } if (west !=
         * null) { mDirectionLayout.addView(west); } if (south != null) {
         * mDirectionLayout.addView(south); } if (north != null) {
         * mDirectionLayout.addView(north); }
         */
        // 下面是根据方向度数显示度数图片数字
        int direction2 = (int) direction;
        String direction3 = "";
        boolean show = false;
        if (direction2 >= 100) {
            direction3 += (String.valueOf(direction2 / 100));
            direction2 %= 100;
            show = true;
        }
        if (direction2 >= 10 || show) {
            direction3 += (String.valueOf(direction2 / 10));
            direction2 %= 10;
        }
        direction3 += (String.valueOf(direction2));
        mAngleLayout.setText(direction3);
        // 下面是增加一个°的图片
        /*
         * ImageView degreeImageView = new ImageView(this);
         * degreeImageView.setImageResource(R.drawable.degree);
         * degreeImageView.setLayoutParams(lp);
         * mAngleLayout.addView(degreeImageView);
         */
    }

    // 获取方向度数对应的图片，返回ImageView
    /*
     * private String getNumber(int number) { int number = 0; LayoutParams lp =
     * new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
     * 
     * image.setLayoutParams(lp); return image; }
     */

    // 调整方向传感器获取的值
    private float normalizeDegree(float degree) {
        return (degree + 720) % 360;
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mHandler.removeCallbacks(mCompassViewUpdater);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        view.removeSensorListener();
    }

}
